package com.itheima.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.category.dao.CategoryMapper;
import com.itheima.category.service.CategoryService;
import com.itheima.goods.pojo.Category;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Result findCategoryListByPage(Long page, Long size) {
        IPage<Category> pageInfo = new Page<>(page, size);
        IPage<Category> catePageInfo = categoryMapper.selectPage(pageInfo, null);

        List<Category> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        PageResult<Category> PageResult = new PageResult<>(total, records);
        return new Result(true, StatusCode.OK,"查询成功",PageResult);
    }

    @Override
    public Result findCategoryListByPageAndSearch(Long page, Long size, Category category) {
        IPage<Category> pageInfo = new Page<>(page, size);

        LambdaQueryWrapper<Category> wrapper = Wrappers.lambdaQuery(Category.class);

        if(category.getName() != null&& !"".equals(category.getName())){
            wrapper.like(Category::getName,category.getName());
        }
        if(category.getIsShow() != null){
            wrapper.eq(Category::getIsShow,category.getIsShow());
        }
        if(category.getIsMenu() != null){
            wrapper.eq(Category::getIsMenu,category.getIsMenu());
        }
        if(category.getSeq() != null){
            wrapper.eq(Category::getSeq,category.getSeq());
        }
        if(category.getParentId() != null){
            wrapper.eq(Category::getParentId,category.getParentId());
        }

        IPage<Category> catePageInfo = categoryMapper.selectPage(pageInfo, wrapper);

        List<Category> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        PageResult<Category> pageR = new PageResult<>(total, records);
        return new Result(true, StatusCode.OK,"查询成功",pageR);
    }

    @Override
    public Result updateCategoryById(Long id, Category category) {
        Category c1 = categoryMapper.selectById(id);
        c1.setName(category.getName());
        c1.setIsShow(category.getIsShow());
        c1.setIsMenu(category.getIsMenu());
        c1.setSeq(category.getSeq());
        c1.setParentId(category.getParentId());
        int i = categoryMapper.updateById(c1);
        return new Result<>(true, StatusCode.OK,"修改成功",i) ;
    }

}
